package com.minelx.datamicroscope.core.query;

import com.minelx.datamicroscope.core.condition.Condition;
import com.minelx.datamicroscope.core.values.CommonField;
import com.minelx.datamicroscope.core.values.CommonTable;

import java.util.List;

import static java.util.Collections.singletonList;

public class CollectingResource {

	private final List<AliasedKey> collectedFields;

	private CollectingResource(List<AliasedKey> collectedFields) {
		this.collectedFields = collectedFields;
	}

	public TrickleQueryBuilder build() {
		CommonTable queriedTable = firstCollectedField().commonTable();
		TrickleQueryBuilder result = TrickleQueryBuilder.query(queriedTable);
		// add collected fields
		collectedFields.forEach(result::addField);
		// add extra conditions
		return result;
	}

	public TrickleQuery appendAndBuild(List<AliasedKey> remainingKeys, List<Condition> conditions) {
		TrickleQueryBuilder result = build();

		// add index fields and conditions
		remainingKeys.forEach(result::addField);
		conditions.forEach(result::addCondition);
		return result.buildQuery();
	}

	public CommonField firstCollectedField() {
		return getCollectedFields().get(0).getKey();
	}

	public List<AliasedKey> getCollectedFields() {
		return collectedFields;
	}

	public static CollectingResource create(AliasedKey collectedField) {
		return new CollectingResource(singletonList(collectedField));
	}

	public static CollectingResource create(List<AliasedKey> collectedFields) {
		return new CollectingResource(collectedFields);
	}
}
